package Concurrency2.Chapter03_CAS_Atomic;

import Concurrency2.Chapter03_CAS_Atomic.beans.Some;
import sun.misc.Unsafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Instruction：模拟生产中的多线程开发, 变化的东西抽取出去
 * <p>
 * Author：@author MaLi
 */
public class T03_AutoIncrement {
    public static void main(String[] args) throws InterruptedException {
        Unsafe unsafe = Utils4Unsafe.getUnsafe();
        Some some = new Some();
        //创建10个线程数量的线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        CountDownLatch count = new CountDownLatch(10);

        Runnable task = new Runnable() {
            @Override
            public void run() {
                System.out.println("ThreadName"+Thread.currentThread().getName());
                //执行10万次累加
                for (int i = 0; i < 100000; i++) {
                    long offset;
                    try {
                        boolean changSuccess;
                        offset = unsafe.objectFieldOffset(Some.class.getDeclaredField("data"));
                        do {
                            changSuccess = unsafe.compareAndSwapObject(some, offset, some.getData(), some.getData() + 1);
                        } while (!changSuccess);
                    } catch (NoSuchFieldException e) {
                        throw new RuntimeException(e);
                    }
                }
                count.countDown();
                System.out.println("ThreadName"+Thread.currentThread().getName()+" ended");
            }
        };
        for (int i = 0; i < 10; i++) {
            pool.submit(task);
        }
        count.await();
        System.out.println(some.getData());
        pool.shutdownNow();
    }
}
